<template>
  <div>
    <!-- <el-row v-loading="listLoading"> -->
    <el-row>
      <el-button @click="setExpanded('O-6067', true)">Expand 扩大</el-button>
      <el-button @click="setExpanded('O-6067', false)">Collapse 折叠</el-button>

      <el-button type="primary" @click="addNode">addNode</el-button>
      <el-button type="success" @click="removeNode('O-6069')">removeNode</el-button>
      <el-button type="info" @click="fit('O-6068')">fit 适应</el-button>
      <el-button type="warning"  @click="layout">swap 改变布局</el-button>
      <el-button type="danger"  @click="compact">compact 紧凑变化</el-button>


      <el-button type="danger"  @click="setActiveNodeCentered()">center Active 活动节点剧中显示</el-button>

      <el-button type="danger"  @click="setCentered('O-6067')">setCentered 指定节点剧中显示</el-button>
      <el-button type="danger"  @click="setHighlighted('O-6067')">mark 标记指定节点</el-button>
      <el-button type="danger"  @click="setUpToTheRootHighlighted('O-6067')">mark root 标记指定节点到根节点</el-button>

      <el-button type="danger"  @click="clearHighlighting">clear mark</el-button>
      <el-button type="danger"  @click="fullscreen">fullscreen</el-button>

      <el-button type="danger"  @click="downloadPdf">downloadPdf</el-button>
      <el-button type="danger"  @click="exportImg">export Img</el-button>
      <el-button type="danger"  @click="exportImgFull">export full img</el-button>
      <el-button type="danger"  @click="exportSvg">exportSvg</el-button>

      <el-button type="danger"  @click="expandAll">expandAll 展开所有</el-button>
      <el-button type="danger"  @click="collapseAll">collapseAll 折叠所有</el-button>

      <el-button type="danger"  @click="connections">add link 连线指定节点</el-button>
      <el-button type="danger"  @click="zoomOut">zoomOut 缩小</el-button>
      <el-button type="danger"  @click="zoomIn">zoomIn 放大</el-button>
    </el-row>

    <input v-model="MyName">
    <el-button @click="changeName">changeName</el-button>
    <div class="chart-container" style="height: 1200px; background-color: white"></div>
  </div>
</template>

<script>
// 功能参考： https://stackblitz.com/edit/web-platform-o5t1ha?file=README.md
// ref : 引用变量， reactive ： 引用对象
import {ref, reactive, toRefs} from 'vue'

/**
 * d3-org-chart 使用注意：
 * id、parentId 为必须字段，不能改名；
 * parentId ：null 表示 根节点
 * 
 */
// npm i d3-org-chart
import { OrgChart } from 'd3-org-chart';
// 测试数据
import { getD3data } from '@/utils/d3.data'

// npm install jspdf --save
import { jsPDF } from "jspdf";

// 引入d3
// import * as d3 from 'd3';

import { getList } from '@/api/family'

export default {
    data() {
        return {
            // data : [{

            // }],
            MyChart : null,
            MyName  : "test",
            index : 0,
            compactcnt : 0,
            actNdCent : 0,

            list: null,
            listLoading: true
        }
    },

    methods: {
        draw(dataFlattened) {
          console.log("draw 参数：");
          console.log(dataFlattened);

          const mappedData = dataFlattened.map((d) => {
            const width = Math.round(Math.random() * 50 + 300);
            const height = Math.round(Math.random() * 20 + 130);
            const cornerShape = ['ORIGINAL', 'ROUNDED', 'CIRCLE'][
              Math.round(Math.random() * 2)
            ];
            const nodeImageWidth = 100;
            const nodeImageHeight = 100;
            const centerTopDistance = 0;
            const centerLeftDistance = 0;
            const expanded = false; //d.id=="O-6"
            let sex = '';
            if (d.sex == 1) {
              sex = "男"
            } else {
              sex = "女"
            }

            const titleMarginLeft = nodeImageWidth / 2 + 20 + centerLeftDistance;
            const contentMarginLeft = width / 2 + 25;
            return {
              nodeId: d.id,
              parentNodeId: d.parentId,
              width: width,
              height: height,
              borderWidth: 1,
              borderRadius: 5,
              borderColor: {
                red: 15,
                green: 140,
                blue: 121,
                alpha: 1,
              },
              backgroundColor: {
                red: 51,
                green: 182,
                blue: 208,
                alpha: 1,
              },
              nodeImage: {
                url: d.imageUrl,
                width: nodeImageWidth,
                height: nodeImageHeight,
                centerTopDistance: centerTopDistance,
                centerLeftDistance: centerLeftDistance,
                cornerShape: cornerShape,
                shadow: false,
                borderWidth: 0,
                borderColor: {
                  red: 19,
                  green: 123,
                  blue: 128,
                  alpha: 1,
                },
              },
              nodeIcon: {
                icon: 'https://to.ly/1yZnX',
                size: 30,
              },
              template: `<div>
                    <div style="margin-left:${titleMarginLeft}px;
                                margin-top:10px;
                                font-size:15px;
                                font-weight:bold;
                          ">姓名：${d.name} </div>
                  <div style="margin-left:${titleMarginLeft}px;
                                margin-top:3px;
                                font-size:13px;
                          ">世代：${d.generations}          排行：${d.ranking}</div>

                  <div style="margin-left:${titleMarginLeft}px;
                        margin-top:3px;
                        font-size:12px;
                  ">性别：${sex}</div>

                  <div style="margin-left:${contentMarginLeft}px;
                              margin-top:15px;
                              font-size:12px;
                              position:absolute;
                              bottom:5px;
                              ">
                        <div>职务：${d.position}</div>
                        <div style="font-size:12px;margin-top:5px">所在城市：${d.address}</div>
                  </div>
                </div>`,
              connectorLineColor: {
                red: 220,
                green: 189,
                blue: 207,
                alpha: 1,
              },
              connectorLineWidth: 5,
              dashArray: '',
              expanded: expanded,
            };
          }
        );

        const chart = new OrgChart()
          .container('.chart-container')
          .data(mappedData)
          .nodeWidth((n) => 250)
          .nodeHeight((n) => 120)
          .compactMarginBetween((d) => 50)
          .onNodeClick((d) => console.log(d + " node clicked"))
          .siblingsMargin((d) => 100)
          .nodeContent((d) => {
            return `
              <div class="outer-wrapper" style="padding-left:70px;padding-top:0px;background-color:none;width:${d.width - 70}px;height:${d.height}px">
                <img style="border-radius:5px;margin-left:-100px;margin-top:-20px" width=60 height=60 src="${d.data.nodeImage.url}"/>

                <div  style="margin-left:-70px;margin-top:-40px;border-radius:5px;color:white;background-color:#2DA7C6;width:${d.width}px;  height:${d.height}px">
                   <div style="margin-left:-30px;padding-top:2px">${d.data.template}</div>
                </div>

                <div style="color:white;margin-top:-37px;margin-left:-65px"> ${d.data._totalSubordinates} 后代 <br/> ${d.data._directSubordinates} 子女</div>
              </div>
              `;
          })
          .render();

          console.log("chart 对象1：");
          console.log(chart);
          console.log("chart 对象11111：");
          this.MyChart = chart;
          console.log("chart 对象2：");

          // this.MyChart = reactive(chart);
          // console.log("chart 对象2：");
          // console.log(this.MyChart);
          // this.$set(this.MyChart, chart);
          // console.log("chart 对象3：");
          // console.log(this.MyChart);
        },

        /**
         * 展开、折叠 ？？？？
         */
        setExpanded(id, flag) {
          console.log(id);
          console.log(this.MyName);
          console.log(this.MyChart);
          // this.MyChart.compact();
          this.MyChart.setExpanded(id, flag).render();
        },

        /**
         * ????
         */
        addNode() {
          this.MyChart.addNode({imageUrl:"https://raw.githubusercontent.com/bumbeishvili/Assets/master/Projects/D3/Organization%20Chart/cto.jpg",id:"root child",parentId:"O-6066",name:"test",progress:[25,20,15,10]});
        },

        /**
         * 删除节点
         */
        removeNode(id) {
          this.MyChart.removeNode(id);
        },

        /**
         * 适应
         */
        fit(id) {
          this.MyChart.fit(id);
        },

        /**
         * 改变布局
         */
        layout() {
          this.MyChart.layout(["right","bottom","left","top"][this.index++%4]).render().fit();
        },

        /**
         * 紧凑变化
         */
        compact() {
          this.MyChart.compact(!!(this.compactcnt++%2)).render().fit();
        },

        /**
         * 活动节点剧中显示
         */
        setActiveNodeCentered() {
          this.MyChart.setActiveNodeCentered(!!(this.actNdCent++%2)).render().fit();
        },

        /**
         * 指定节点剧中显示
         */
        setCentered(id) {
          this.MyChart.setCentered(id).render();
        },

        /**
         * 标记指定节点
         */
        setHighlighted(id) {
          this.MyChart.setHighlighted(id).render();
        },

        /**
         * 标记指定节点到根节点
         */
        setUpToTheRootHighlighted(id) {
          this.MyChart.setUpToTheRootHighlighted(id).render().fit();
        },

        /**
         * 清除标记节点
         */
        clearHighlighting() {
          this.MyChart.clearHighlighting();
        },

        /**
         * 全屏
         */
        fullscreen() {
          this.MyChart.fullscreen('body');
        },

        /**
         * 导出图片
         */
        exportImg() {
          this.MyChart.exportImg();
        },

        /**
         * 导出图片
         */
        exportImgFull() {
          this.MyChart.exportImg({full:true});
        },

        /**
         * 导出整个画布
         */
        exportSvg() {
          this.MyChart.exportSvg();
        },

        /**
         * 展开所有
         */
        expandAll() {
          this.MyChart.expandAll();
        },

        /**
         * 折叠所有
         */
        collapseAll() {
          this.MyChart.collapseAll();
        },

        /**
         * https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.3.1/jspdf.umd.min.js
         */
        downloadPdf() {
          this.MyChart.exportImg({
            save: false,
            onLoad: (base64) => {
              // var pdf = new jspdf.jsPDF();
              var pdf = new jsPDF();
              var img = new Image();
              img.src = base64;
              img.onload = function () {
                pdf.addImage(
                  img,
                  'JPEG',
                  5,
                  5,
                  595 / 3,
                  ((img.height / img.width) * 595) / 3
                );
                pdf.save('chart.pdf');
              };
            },
          });
        },

        
        /**
         * 连线（从 from 连到 to 的位置）
         */
        connections() {
          this.MyChart.connections([{from:"O-6069",to:"O-6070",label:"Conflicts of interest"}]).render();
        },

        /**
         * 缩小
         */
        zoomOut() {
          this.MyChart.zoomOut();
        },

        /**
         * 放大
         */
        zoomIn() {
          this.MyChart.zoomIn();
        },



        /**
         * 动态加载数据
         */
        fetchData() {
          // this.listLoading = true
          getList().then(response => {
            // console.log("fetchData");
            // console.log(response);
            this.list = response.data
            console.log("fetchData");
            console.log(this.list);
            this.draw(this.list);
            // return response.data;
            // this.listLoading = false
          })
        },

        changeName() {
          this.MyName = "xxxxx"
        }
    },

    
    mounted() {
        // this.draw(getD3data());
        console.log("mounted");
        console.log(getD3data());
        this.fetchData();
        // console.log("mounted");
        // console.log(this.list);

        // 获取不到 data 里的数据
        // this.draw(this.list);
    },

    created() {
      // console.log("created");
      // this.list = this.fetchData();
      // console.log(this.list);
      // // TODO 设置动态数据
      // this.draw(this.list);
    }

}
</script>


<style>

</style>